// FourChanBoardCategory.cs
// 
// Copyright © 2009 FreeZzaph
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace LibFreeZzaph.FourChan
{
	
	internal sealed class FourChanBoardCategory : Category
	{
		private static readonly Regex pageLinkRegex =
			new Regex(@"\[<a.+?href=""?([^"">]+)""?.*?>Reply</a>\]", RegexOptions.Compiled);
		
		private string categoryUrl;
		
		public FourChanBoardCategory(string name, string description, string categoryUrl)
			: base (name, description, imageFilter)
		{
			this.categoryUrl = categoryUrl;
		}
				
		public override sealed IList<Uri> FetchUris(uint start, int count)
		{
			// Calculate offsets, start positions and counts
			uint page = start == 0 ? 0 : (start - 1) / 10;
			uint pageStart = start % 10;
			uint currentCount = 0;
			int realCount = count;
			if (realCount == -1) realCount = 10 - (int)pageStart;
			
			List<Uri> urls = new List<Uri>();
			List<string> duplicateCheck = new List<string>();
			while (currentCount < realCount && page <= 10)
			{
				Uri categoryUrl;
				categoryUrl = new Uri(this.categoryUrl);
				if (page != 0)
				{
					categoryUrl = new Uri(categoryUrl, string.Format("{0}.html", page));
				}
				
				string categoryData = FreeZzaphUtility.FetchUrl(categoryUrl);
				
				Match match = pageLinkRegex.Match(categoryData);
				while (match.Success && pageStart > 0)
				{
					match = match.NextMatch();
					pageStart--;
				}
				while (match.Success && currentCount < realCount)
				{
					string matchUrl = match.Groups[1].ToString();
					
					if (!duplicateCheck.Contains(matchUrl))
					{
						try
						{
							duplicateCheck.Add(matchUrl);
							Uri url = new Uri(categoryUrl, matchUrl);
							urls.Add(url);
							currentCount++;
						}
						catch (UriFormatException)
						{
							// Invalid URL
						}
					}
				
					match = match.NextMatch();
				}
			
				// Go to next page
				page++;
			}
			
			return urls;
		}
		
	}
}
